import { App } from "vue"
import { RouteRecordRaw, createRouter, createWebHashHistory } from "vue-router"
import { useUserInfoStore } from "@/store/useStore"
import * as http from "@/request/http"
import { ElMessage } from 'element-plus';

const routes: RouteRecordRaw[] = [
    {
        path: "/login",
        component: () => import("@/page/login/index.vue")
    },

]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const userInfo = useUserInfoStore()
    const token = localStorage.getItem("token")
    if (token && userInfo.menus.length === 0) {
        http.admin.userInfo().then(res => {
            if (res.code === 200) {
                userInfo.upDateMenus(res.data.menus)
                userInfo.username = res.data.username
                let menuRouer = userInfo.getMenuRoutrs
                for (let k in menuRouer) {
                    let routerObj: RouteRecordRaw = {
                        path: "/" + menuRouer[k].name,
                        name: menuRouer[k].name,
                        component: () => import("@/page/home/index.vue"),
                        children: []
                    }
                    menuRouer[k].children?.forEach(item => {
                        routerObj.children?.push({
                            path: item.name,
                            name: item.name,
                            component: () => import(`@/page/${menuRouer[k].name}/${item.name}.vue`),
                            meta: {
                                targetRouterPath: "/" + menuRouer[k].name,
                                targetRouterName: menuRouer[k].title,
                                targetSubRouterName: item.title
                            }
                        })
                        if (routerObj.children?.length != 0) {
                            routerObj.redirect = "/" + menuRouer[k].name + "/" + menuRouer[k].children![0].name
                        }
                    })
                    router.addRoute(routerObj)
                }

                router.addRoute({
                    path: "/",
                    component: () => import("@/page/home/index.vue"),
                    children: [
                        { path: 'index', component: () => import("@/page/index/index.vue") }
                    ]
                })
                next(to.fullPath)
            } else {
                localStorage.removeItem("token")
                next("/login")
            }
        })
    } else if (!token && to.fullPath != "/login") {
        next("/login")
    } else if (token && to.fullPath === "/login" && userInfo.menus.length != 0) {
        ElMessage.warning("请先退出登录再进行登录。")
        next(from.fullPath);
    }
    else {
        next()
    }
})

export default router
export function initRouter(app: App<Element>) {
    app.use(router)
}